package com.ph.shopping.facade.permission.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ph.shopping.facade.mapper.UserRoleMapper;
import com.ph.shopping.facade.permission.entity.UserRole;
import com.ph.shopping.facade.permission.service.constant.RoleIDEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.mapper.MenuMapper;
import com.ph.shopping.facade.mapper.RoleMapper;
import com.ph.shopping.facade.mapper.RoleMenuMapper;
import com.ph.shopping.facade.permission.dto.RoleDto;
import com.ph.shopping.facade.permission.dto.RoleMenuDto;
import com.ph.shopping.facade.permission.entity.Role;
import com.ph.shopping.facade.permission.service.IRoleService;
import com.ph.shopping.facade.permission.vo.MenuTreeVo;
import com.ph.shopping.facade.permission.vo.MenuVo;
import com.ph.shopping.facade.permission.vo.RoleVo;

/**
 * @项目：phshopping-service-permission
 * @描述：
 * @作者： Mr.zheng
 * @创建时间：2017-03-17
 * @Copyright @2017 by Mr.zheng
 */
@Component
@Service(version="1.0.0")
public class RoleService extends BaseService implements IRoleService{

	private static final Logger logger = LoggerFactory.getLogger(RoleService.class);

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
	private RoleMenuMapper roleMenuMapper;
    @Autowired
	private MenuMapper menuMapper;
	@Autowired
    private UserRoleMapper userRoleMapper;

	/**
	 * 新增角色
	 * @param role
	 * @return Result
	 * @throws BizException
	 */
	@Override
    @Transactional
    public Result addRole(Role role) throws BizException{
    	try {
			role.setCreateTime(new Date());
			role.setUpdateTime(new Date());
			role.setStatus(1);//默认为启用状态
			roleMapper.insert(role);
			return getResult(ResultEnum.SUCCESS);
		} catch (Exception ex) {
			logger.error("新增角色异常，ex={}", ex);
			throw new BizException("新增角色服务器异常");
		}
    }

	/**
	 * 修改角色
	 * @param role
	 * @return Result
	 * @throws BizException
	 */
	@Override
    @Transactional
    public Result updateRole(Role role) throws BizException{
    	try {
			role.setUpdateTime(new Date());
			roleMapper.updateByPrimaryKeySelective(role);
			return getResult(ResultEnum.SUCCESS);
		} catch (Exception ex) {
			logger.error("修改角色异常，ex={}", ex);
			throw new BizException("修改角色服务器异常");
		}

    }

	/**
	 * 删除角色
	 * @param role
	 * @return Result
	 * @throws BizException
	 */
	@Override
    @Transactional
    public Result deleteRole(Role role) throws BizException{
    	try {
			//默认角色不能删除 角色id 1,2,3,4,5,6 或者 如果角色存在用户绑定，不能删除
			UserRole userRole = new UserRole();
			userRole.setRoleID(role.getId());
			if (CollectionUtils.isNotEmpty(userRoleMapper.selectUserRole(userRole))
					|| null != RoleIDEnum.getRoleEnumByCode(role.getId()))
				return getResult(ResultEnum.ROLE_CAN_NOT_DELETE);
			roleMapper.delete(role);
			roleMenuMapper.deleteMenuByRoleID(role.getId());
			return getResult(ResultEnum.SUCCESS);
		} catch (Exception ex) {
			logger.error("删除角色异常，ex={}", ex);
			throw new BizException("删除角色服务器异常");
		}
    }

	/**
	 * 启用或者停用角色
	 * @param role
	 * @return Result
	 * @throws BizException
	 */
	@Override
	@Transactional
	public Result enableOrDisableRole(Role role) throws BizException {
		try {
			Role dbRole = new Role();
			dbRole.setUpdateTime(new Date());
			dbRole.setId(role.getId());
			dbRole.setStatus(role.getStatus());
			roleMapper.updateByPrimaryKeySelective(dbRole);
			return getResult(ResultEnum.SUCCESS);
		} catch (Exception ex) {
			logger.error("启用或者停用角色异常，ex={}", ex);
			throw new BizException("启用或者停用角色服务器异常");
		}
	}

	/**
	 * 分页查询角色信息
	 * @param role
	 * @param page
	 * @return
	 */
	public Result getRoleByPage(PageBean page,RoleDto role) {
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<RoleVo> list=(Page<RoleVo>)roleMapper.getRoleByPage(role);
		PageInfo<RoleVo>pageInfo=new PageInfo<RoleVo>(list);
		return getResult(ResultEnum.SUCCESS,pageInfo.getList(),pageInfo.getTotal());
	}

	/**
	 * 查询所有角色
	 * @return
	 */
	@Override
	public Result getAllRole() {
		return getResult(ResultEnum.SUCCESS,roleMapper.getAllRole());
	}

	/**
	 * 通过角色id查询菜单
	 * @param roleID
	 * @return
	 */
	@Override
	public Result getRoleMenuByRoleID(Long roleID) {
		List<MenuVo> list = menuMapper.getAllMenuByRoleID(roleID);
		List<Long> menuIds = roleMenuMapper.selectRoleMenu(roleID);
		//treevo 转换
		return getResult(ResultEnum.SUCCESS,paramsTrans(list,menuIds));
	}


	/**
	 * 修改角色权限
	 * @param roleMenuDto
	 * @return Result
	 * @throws BizException
	 */
	@Override
	@Transactional
	public Result updateRoleMenu(RoleMenuDto roleMenuDto) throws BizException {
    	try {
			roleMenuMapper.deleteMenuByRoleID(roleMenuDto.getRoleID());
			roleMenuMapper.insertRoleMenu(roleMenuDto.getRoleID(),roleMenuDto.getMenuID());
			return getResult(ResultEnum.SUCCESS);
		} catch (Exception ex) {
			logger.error("修改角色权限异常，ex={}", ex);
			throw new BizException("修改角色权限服务器异常");
		}
	}
	
	/**
	 * 判断角色拥有的菜单
	 * @param menuVos
	 * @param menuIds
	 */
	private List<MenuTreeVo> paramsTrans(List<MenuVo> menuVos, List<Long> menuIds) {
		List<MenuTreeVo> list = null;
		MenuTreeVo menuTreeVo;
		if (CollectionUtils.isNotEmpty(menuVos)) {
			list = new ArrayList<>();
			for (MenuVo menuVo : menuVos) {
				menuTreeVo = new MenuTreeVo();
				transVo(menuTreeVo, menuVo);
				if (CollectionUtils.isNotEmpty(menuIds)) {
					for (Long menuId : menuIds) {
						if (menuId.equals(menuVo.getId())) {
							menuTreeVo.setChecked(true);
							break;
						}
					}
				}
				list.add(menuTreeVo);
			}
		}
		return list;
	}
	

	
	private void transVo(MenuTreeVo menuTreeVo, MenuVo menuVo) {
		menuTreeVo.setId(menuVo.getId());
		menuTreeVo.setpId(menuVo.getParentId());
		menuTreeVo.setName(menuVo.getMenuName());
		
	}
	
	@Override
	public Result getRoleById(Integer id) {
		Role r=roleMapper.selectByPrimaryKey(Long.parseLong(id.toString()));
		return getResult(ResultEnum.SUCCESS, r);
	}

}
